import { loginByUsername, logout, getUserInfo } from "@/api/login";
import {
  getToken,
  setToken,
  removeToken,
  setBrandIsImproved,
  removeBrandIsImproved,
} from "@/utils/auth";

const user = {
  state: {
    user: "",
    status: "",
    code: "",
    token: getToken(),
    name: "",
    storeId: "",
    storeName: "",
    avatar: "",
    introduction: "",
    roles: [],
    perms: [],
    menuIds: [],
    setting: {
      articlePlatform: [],
    },
  },

  mutations: {
    SET_CODE: (state, code) => {
      state.code = code;
    },
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_INTRODUCTION: (state, introduction) => {
      state.introduction = introduction;
    },
    SET_SETTING: (state, setting) => {
      state.setting = setting;
    },
    SET_STATUS: (state, status) => {
      state.status = status;
    },
    SET_NAME: (state, name) => {
      state.name = name;
    },
    SET_STORE_ID: (state, storeId) => {
      state.storeId = storeId;
    },
    SET_STORE_NAME: (state, storeName) => {
      state.storeName = storeName;
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar;
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
    SET_PERMS: (state, perms) => {
      state.perms = perms;
    },
    SET_MENUIDS: (state, menuIds) => {
      state.menuIds = menuIds
    }
  },

  actions: {
    // 用户名登录
    LoginByUsername({ commit }, userInfo) {
      const username = userInfo.username.trim();
      const password = userInfo.password;
      const code = userInfo.code;
      const uuid = userInfo.uuid;
      return new Promise((resolve, reject) => {
        loginByUsername(username, password, code, uuid)
          .then((response) => {
            const isImproved = response.data.data.brandIsImproved;
            const token = response.data.data.sessionId;
            commit("SET_TOKEN", token);
            setToken(token);
            setBrandIsImproved(isImproved);
            resolve(isImproved);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 获取用户信息
    GetUserInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getUserInfo(state.token)
          .then((response) => {
            const data = response.data.data;

            if (data.perms && data.perms.length > 0) {
              // 验证返回的perms是否是一个非空数组
              commit("SET_PERMS", data.perms);
            } else {
              // reject("getInfo: perms must be a non-null array !");
            }
            if (data.menuIdList && data.menuIdList.length > 0) { // 验证返回的perms是否是一个非空数组
              commit('SET_MENUIDS', data.menuIdList)
            }

            commit("SET_ROLES", data.roles);
            commit("SET_NAME", data.name);
            commit("SET_STORE_ID", data.brandInfo?.id || "");
            commit("SET_STORE_NAME", data.brandInfo?.name || "");
            commit("SET_AVATAR", data.avatar);
            commit("SET_INTRODUCTION", data.introduction);
            resolve(response);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 外部token登录
    LoginByToken({ commit, state }, token) {
      commit("SET_TOKEN", token);
      setToken(token);
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token)
          .then(() => {
            commit("SET_TOKEN", "");
            commit("SET_ROLES", []);
            commit("SET_PERMS", []);
            commit('SET_MENUIDS', [])
            removeToken();
            removeBrandIsImproved();
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise((resolve) => {
        commit("SET_TOKEN", "");
        removeToken();
        removeBrandIsImproved();
        resolve();
      });
    },

    // 动态修改权限
    ChangeRoles({ commit, dispatch }, role) {
      return new Promise((resolve) => {
        commit("SET_TOKEN", role);
        setToken(role);
        getUserInfo(role).then((response) => {
          const data = response.data;
          commit("SET_ROLES", data.roles);
          commit("SET_PERMS", data.perms);
          commit('SET_MENUIDS', data.menuIds)
          commit("SET_NAME", data.name);
          commit("SET_AVATAR", data.avatar);
          commit("SET_INTRODUCTION", data.introduction);
          dispatch("GenerateRoutes", data); // 动态修改权限后 重绘侧边菜单
          resolve();
        });
      });
    },
  },
};

export default user;
